<template>
  <div>
    <p style="font-size: 20px">{{ msg }}</p>
    <!-- 显示药品列表 -->
    <el-table :data="pagedDrug" style="width: 100%">
      <el-table-column prop="new_id" label="编号" width="80"/>
      <el-table-column prop="drug_name" label="药名"/>
      <el-table-column prop="drug_inprice" label="进价"/>
      <el-table-column prop="drug_outprice" label="售价"/>
      <el-table-column prop="drug_type" label="药品类别"/>
      <el-table-column align="right">
        <!--        delete与edit的实现-->
        <!--        Delete button -->
        <template #default="scope">
          <div style="display: flex;align-items: center;" v-if="haspermission(['admin','manager'])">
            <!-- Edit button with popover -->
            <el-button size="small" type="danger" @click="open_delete(scope.row)">Delete</el-button>
            <el-popover placement="right" :width="320" trigger="click">
              <template #reference>
                <el-button size="small" @click="setValue(scope.row)">Edit</el-button>
              </template>
              <div>
                <form @submit="handleEdit">
                  <p>向后端修改药品信息:</p>
                  <label>药名：</label>
                  <el-input
                      v-model="drugEdit.drug_name"
                      style="width: 240px"
                      show-word-limit
                      type="text"
                  />
                  <label>进价：</label>
                  <el-input
                      v-model="drugEdit.drug_inprice"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=number
                  /><label>售价：</label>
                  <el-input
                      v-model="drugEdit.drug_outprice"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=number
                  />
                  <label>类别：</label>
<!--                  <el-input-->
<!--                      v-model="drugEdit.drug_type"-->
<!--                      style="width: 240px"-->
<!--                      maxlength="20"-->
<!--                      show-word-limit-->
<!--                      type="text"-->
<!--                  />-->
                  <el-radio-group v-model="drugEdit.drug_type">
                  <el-radio label="GRANULE">颗粒剂</el-radio>
                  <el-radio label="TABLET">片剂</el-radio>
                  <el-radio label="CAPSULE">胶囊</el-radio>
                  <el-radio label="DECOCTION_EXTRACT">煎膏剂</el-radio>
                  <el-radio label="PILLET">滴丸剂</el-radio>
                  <el-radio label="TEMPORARY">暂定</el-radio>
                </el-radio-group>
                  <div style="margin: 20px 0"/>
                  <el-button type="info" round @click="handleEdit(scope.row)" size="small">提交修改</el-button>
                </form>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 30px"
        layout="prev, pager, next"
        :total="total"
        v-model="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />

    <div style="display: flex; align-items: center;">
      <!-- 添加药品的表单 -->
      <form @submit="drugSubmit" ref="addForm">
        <h3>向后端添加药品的表单:</h3>
        <el-input
            v-model="inputDrug.drug_name"
            style="width: 240px"
            maxlength="20"
            placeholder="药品名称"
            show-word-limit
            type="text"
        />
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputDrug.drug_inprice"
            maxlength="20"
            style="width: 240px"
            placeholder="药品进价"
            show-word-limit
            type="number"
        /><div style="margin: 5px 0"/>
        <el-input
            v-model="inputDrug.drug_outprice"
            maxlength="20"
            style="width: 240px"
            placeholder="药品售价"
            show-word-limit
            type="number"
        /><div style="margin: 5px 0"/>
        <div>
          <el-select v-model="inputDrug.drug_type" placeholder="Select"
                     style="background-color: darkslategrey; color: #fff;">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <hr>
        <el-button type="success" round @click="drugSubmit">提交</el-button>
      </form>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询药品的表单1</h3>
        <label>药品名称：</label>
        <el-input type="text" style="width: 240px" v-model="title_pattern"/>
        <div style="margin: 20px 0"/>
        <el-popover placement="right" :width="600" trigger="click">
          <template #reference>
            <el-button type="info" @click="findDrug">按药名查找</el-button>
          </template>
          <el-table :data="sdrug">
            el-table-column prop="new_id" label="编号" width="80"/>
            <el-table-column prop="drug_name" label="药名"/>
            <el-table-column prop="drug_inprice" label="进价"/>
            <el-table-column prop="drug_outprice" label="售价"/>
            <el-table-column prop="drug_type" label="药品类别"/>
          </el-table>
        </el-popover>
      </div>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询药品的表单2</h3>
        <label>药品类别：</label>
        <el-input type="text" style="width: 240px" v-model="type"/>
        <div style="margin: 20px 0"/>
        <el-popover placement="right" :width="600" trigger="click">
          <template #reference>
            <el-button type="info" @click="findDrug2">按类别查找</el-button>
          </template>
          <el-table :data="sdrug">
            el-table-column prop="new_id" label="编号" width="80"/>
            <el-table-column prop="drug_name" label="药名"/>
            <el-table-column prop="drug_inprice" label="进价"/>
            <el-table-column prop="drug_outprice" label="售价"/>
            <el-table-column prop="drug_type" label="药品类别"/>
          </el-table>
        </el-popover>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, h, onMounted, ref, watch} from 'vue';
import {getDrugs, postDrug, deleteDrug, updateDrug, findByDrugTitle, findByDrugType} from '@/api/api'
import {ElMessage, ElMessageBox} from "element-plus";
import {useLoginStore} from "@/stores";

const store = useLoginStore();

function haspermission(allowance: string[]) {
  return allowance.indexOf(store.role) !== -1;
}
const msg = ref('欢迎来到药品管理板块');

const inputDrug = ref({
  drug_name:"",
  drug_inprice:Number,
  drug_outprice:Number,
  drug_type:""
});

const options = [
  {
    label: '颗粒剂',
    value: 'GRANULE',
  },
  {
    label: '片剂',
    value: 'TABLET',
  },
  {
    label: '胶囊',
    value: 'CAPSULE',
  },
  {
    label: '煎膏剂',
    value: 'DECOCTION_EXTRACT',
  },
  {
    label: '滴丸剂',
    value: 'PILLET',
  },
  {
    label: '暂定',
    value: 'TEMPORARY',
  }
];
//增
async function drugSubmit() {
  try {
    const response = await postDrug(inputDrug.value.drug_name,inputDrug.value.drug_inprice,inputDrug.value.drug_outprice,inputDrug.value.drug_type);
    console.log(response);
    await loadDrugs();
    // 清空输入字段
    inputDrug.value = {drug_name:"", drug_inprice:Number, drug_outprice:Number, drug_type:""};
  } catch (error) {
    console.error('Error submitting drug:', error);
    // 在这里可以添加错误处理的逻辑，比如显示错误信息给用户
  }
}

//删
async function deleteDrugAndHandleResponse(id: number) {
  try {
    const response = await deleteDrug(id);
    console.log('Drug deleted successfully', response);
    await loadDrugs()
  } catch (error) {
    console.error('Error deleting Drug', error);
  }
}

const open_delete = (obj: any) => {
  ElMessageBox({
    title: 'Message',
    message: h('p', null, [
      h('span', null, '请注意删除操作是不可逆的'),
      h('i', {style: 'color: teal'}, '数据库会同步变化'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消删除',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        deleteDrugAndHandleResponse(obj.id);
        // window.location.reload()
        done();
      } else {
        done();
      }
    },
  }).then((action) => {
    ElMessage({
      type: 'info',
      message: `操作结果: ${action === 'confirm' ? '删除成功' : '已取消删除'}`,
    });
  });
}

//改
const drugEdit = ref({
  drug_name:"",
  drug_inprice:Number,
  drug_outprice:Number,
  drug_type:""
})

function setValue(obj: any) {
  drugEdit.value.drug_name = obj.drug_name;
  drugEdit.value.drug_inprice = obj.drug_inprice;
  drugEdit.value.drug_outprice = obj.drug_outprice;
  drugEdit.value.drug_type = obj.drug_type;
}


async function handleEdit(obj: any) {
  try {
    const response = await updateDrug(obj.id, drugEdit.value)
    console.log("Drug edit successfully", response)
    await loadDrugs()
    ElMessage({
      type: 'info',
      message: `操作结果:'修改成功'`,
    });
  } catch (error) {
    console.error(error);
  }
}

//查
const drugs = ref([
  {id: 1, drug_name:"", drug_inprice:Number, drug_outprice:Number, drug_type:"", new_id: 0},
  {id: 2, drug_name:"", drug_inprice:Number, drug_outprice:Number, drug_type:"", new_id: 0},
])
let currentPage = ref(1)
const pageSize = ref(6)
const total = ref(drugs.value.length) // 计算总记录数

watch(drugs, (newValue) => {
  total.value = newValue.length;
});
const pagedDrug = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  return drugs.value.slice(startIndex, endIndex);
});

function handlePageChange(newPage: number) {
  currentPage.value = newPage
}

async function loadDrugs() {
  try {
    const response = await getDrugs();
    // 假设 response.data 是一个药品数组
    drugs.value = response.data;
    let new_index = 1;
    for (let oneMoney of drugs.value) {
      oneMoney.new_id = new_index;
      new_index++;
    }
  } catch (error) {
    // 处理错误情况
    console.error('Error loading drugs:', error);
  }
}
onMounted(() => {
  loadDrugs();
});

//特殊查寻
const title_pattern = ref('')
const type = ref('')
const sdrug = ref([
  {id: 1, drug_name:"", drug_inprice:0, drug_outprice:0, drug_type:"", new_id: 0},
])

async function findDrug() {
  try {
    const response = await findByDrugTitle(title_pattern.value);
    sdrug.value = response.data
    console.log(response)
    console.log(sdrug.value)
    let index = 1
    for (let i of sdrug.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
async function findDrug2() {
  try {
    const response = await findByDrugType(type.value);
    sdrug.value = response.data
    console.log(response)
    console.log(sdrug.value)
    let index = 1
    for (let i of sdrug.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
</script>